<!-- 设备管理-设备列表页面 -->
<template>
  <div class="app-container">
    <px-form v-show="showSearch" ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
      <px-form-item label="化学品名称">
        <px-select v-model="queryParams.chemical" placeholder="请选择化学品名称" clearable style="width: 240px" filterable>
          <px-option v-for="dict in querychemicalList" :key="dict.chemical" :label="dict.chemical" :value="dict.chemical" />
        </px-select>
      </px-form-item>
      <px-form-item label="有效开始日期" style="width: 516px !important">
        <px-date-picker
          v-model="dateRange"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :default-time="defaultTime"
        />
      </px-form-item>
      <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery('search')">搜索</px-button>
      <px-button style="margin-top: -17px" icon="" @click="resetQuery">重置</px-button>
    </px-form>

    <px-row :gutter="10" class="mb8">
      <px-col :span="1.5">
        <px-button v-has="'PRECURSOR_WARRANT_ADD'" type="primary" icon="" @click="handleAdd">新增</px-button>
      </px-col>
      <!-- <px-col :span="1.5">
        <px-button type="primary" plain icon="" @click="handleExport">导出报表</px-button>
      </px-col> -->
    </px-row>

    <px-table
      v-if="!equipopen && !equipopenDetail"
      v-loading="loading"
      :data="typeList"
      height="calc(100vh - 329px)"
      show-overflow-tooltip
      border
      @selection-change="handleSelectionChange"
    >
      <!-- <px-table-column type="selection" width="40" /> -->
      <px-table-column label="序号" width="60" align="center" fixed="left">
        <template #default="{ $index }">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
        </template>
      </px-table-column>

      <px-table-column label="化学品名称" prop="chemical">
        <template #default="scope">
          <span>{{ scope.row.chemical ? scope.row.chemical : "-" }}</span>
        </template>
      </px-table-column>

      <px-table-column label="购买证编号" width="160" prop="permitOutNumber">
        <template #default="scope">
          <span>{{ scope.row.permitOutNumber }}</span>
        </template>
      </px-table-column>

      <px-table-column label="可购入数量(吨)" prop="totalQuantity">
        <template #default="scope">
          <span>{{ scope.row.totalQuantity }}</span>
        </template>
      </px-table-column>
      <px-table-column label="已购入数量(吨)" prop="usedQuantity">
        <template #default="scope">
          <span>{{ scope.row.usedQuantity }}</span>
        </template>
      </px-table-column>
      <px-table-column label="剩余可购数量(吨)" prop="remainQuantity">
        <template #default="scope">
          <span v-if="scope.row.quantityFlag == '0' || scope.row.quantityFlag == null">{{
            scope.row.remainQuantity ? scope.row.remainQuantity : "-"
          }}</span>
          <span v-if="scope.row.quantityFlag == '1'" class="status-value2">{{ scope.row.remainQuantity ? scope.row.remainQuantity : "-" }}</span>
        </template>
      </px-table-column>
      <px-table-column label="有效日期">
        <template #default="scope">
          <span v-if="scope.row.expireFlag == '0' || scope.row.expireFlag == null"
            >{{ scope.row.effectiveDateFrom }}-{{ scope.row.effectiveDateTo }}</span
          >
          <span v-if="scope.row.expireFlag == '1'" class="status-value2">{{ scope.row.effectiveDateFrom }} - {{ scope.row.effectiveDateTo }}</span>
        </template>
      </px-table-column>
      <px-table-column label="状态" prop="gasType">
        <template #default="scope">
          <span v-if="scope.row.useStatus == '1'" class="status-value"><span class="status-icon" />使用中</span>
          <span v-else-if="scope.row.useStatus == '2'" class="status-value2"><span class="status-icon2" />已核销</span>
          <span v-else>无</span>
        </template>
      </px-table-column>
      <px-table-column fixed="right" label="操作" align="center" width="140">
        <template #default="scope">
          <px-button v-has="'PRECURSOR_WARRANT_DETAIL'" link type="primary" @click="handleDetail(scope.row.id)">
            <px-tooltip class="box-item" content="详情" placement="top">
              <px-icon><Tickets /></px-icon> </px-tooltip
          ></px-button>
          <px-button v-if="scope.row.useStatus != '2'" v-has="'PRECURSOR_WARRANT_EDITORD'" link type="primary" @click="handleEditor(scope.row.id)">
            <px-tooltip class="box-item" content="编辑" placement="top">
              <px-icon><EditPen /></px-icon> </px-tooltip
          ></px-button>
          <px-button v-if="scope.row.status != 'INVALID'" v-has="'PRECURSOR_WARRANT_DELETE'" link type="danger" @click="handleDelete(scope.row)"
            ><px-tooltip class="box-item" content="删除" placement="top">
              <px-icon><Delete /></px-icon> </px-tooltip
          ></px-button>
        </template>
      </px-table-column>
      <template #empty>
        <px-empty :image-size="150" />
      </template>
    </px-table>

    <pagination
      v-if="!equipopen && !equipopenDetail"
      v-show="total > 0"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      style="margin-bottom: -10px"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->

    <px-scrollbar v-if="equipopen" class="editorEquip">
      <px-button style="margin-left: 24px" type="primary" :icon="ArrowLeft" @click="cancel">返回</px-button>
      <div class="px-descriptions__title" style="margin: 20px 0 0 20px">基本信息</div>
      <px-row style="padding: 20px">
        <px-col :span="8">
          <px-descriptions class="margin-top" :column="1" border>
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">购买证编码:</div>
              </template>
              {{ equipdata.permitOutNumber }}
            </px-descriptions-item>
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">可购入数量:</div>
              </template>
              {{ equipdata.totalQuantity }}
            </px-descriptions-item>
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">有效时间:</div>
              </template>
              {{ equipdata.effectiveDateFrom }}- {{ equipdata.effectiveDateTo }}
            </px-descriptions-item>
          </px-descriptions>
        </px-col>
        <px-col :span="8">
          <px-descriptions class="center2" :column="1" border>
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">化学品名称:</div>
              </template>
              {{ equipdata.chemical }}
            </px-descriptions-item>
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">单位:</div>
              </template>
              {{ equipdata.purchaseUnit }}
            </px-descriptions-item>
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">限次类型:</div>
              </template>
              {{ equipdata.limitTimesTypeName }}
            </px-descriptions-item>
          </px-descriptions>
        </px-col>
        <px-col :span="8">
          <px-descriptions class="center2" :column="1" border>
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">销售单位:</div>
              </template>
              {{ equipdata.salesCompany }}
            </px-descriptions-item>
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">剩余可购入数量:</div>
              </template>
              {{ equipdata.remainQuantity }}
            </px-descriptions-item>
            <px-descriptions-item>
              <template #label>
                <div class="cell-item">办理人:</div>
              </template>
              {{ equipdata.responsiblePerson }}
            </px-descriptions-item>
          </px-descriptions>
        </px-col>
      </px-row>

      <div style="width: 100%; padding: 0 0 0 20px; clear: both">
        <div class="px-descriptions__title" style="padding: 20px 0">过磅照片</div>
        <PhotoUpload photoType="view" :photoData="{ moduleName: 'GENERAL_CHEMICALS' }" :photoList="equipdata.permitAttachment" />
      </div>
      <div style="width: 100%; padding: 0 0 0 20px; clear: both">
        <div class="px-descriptions__title" style="padding: 20px 0">送货单</div>
        <PhotoUpload photoType="view" :photoData="{ moduleName: 'GENERAL_CHEMICALS' }" :photoList="equipdata.legalAttachment" />
      </div>
    </px-scrollbar>
    <px-scrollbar v-if="equipopenDetail" class="addEquip">
      <px-button style="margin-left: 24px" type="primary" :icon="ArrowLeft" @click="equipopenDetailcancel">返回</px-button>
      <px-form
        ref="detailruleFormRef"
        :disabled="fromdisable"
        :rules="rules"
        :model="equipdata"
        :inline="true"
        class="demo-form-inline"
        label-width="160px"
      >
        <div
          class="box-card1"
          :style="{
            height: jibenxinxiFlg == true ? '' : '42px'
          }"
        >
          <div class="card-header" @click="setqingdanFlg()">
            <div class="card-title">基本信息</div>
            <div class="card-main">
              <px-icon v-if="!jibenxinxiFlg"><ArrowDown /></px-icon>
              <px-icon v-else><ArrowUp /></px-icon>
            </div>
          </div>
          <div class="form-div">
            <px-row>
              <px-col :span="8">
                <px-form-item label="购买证编码" prop="permitOutNumber">
                  <px-input v-model="equipdata.permitOutNumber" placeholder="请输入" clearable /> </px-form-item
              ></px-col>
              <px-col :span="8">
                <px-form-item label="化学品名称" prop="chemicalCode">
                  <px-select
                    v-model="equipdata.chemicalCode"
                    placeholder="请选择化学品名称"
                    clearable
                    style="width: calc(100% - 100px)"
                    filterable
                    @change="changechemicalCode"
                  >
                    <px-option v-for="dict in querychemicalList" :key="dict.chemicalCode" :label="dict.chemical" :value="dict.chemicalCode" />
                  </px-select> </px-form-item
              ></px-col>
              <px-col :span="8">
                <px-form-item label="销售单位" prop="salesCompany">
                  <px-select v-model="equipdata.salesCompany" placeholder="请选择系统" clearable style="width: calc(100% - 100px)" filterable>
                    <px-option v-for="dict in salesCompanyList" :key="dict.itemValue" :label="dict.itemName" :value="dict.itemName" />
                  </px-select> </px-form-item
              ></px-col>
              <px-col :span="8">
                <px-form-item label="可购入数量" prop="totalQuantity">
                  <px-input-number
                    v-model="equipdata.totalQuantity"
                    style="width: calc(100% - 100px)"
                    :precision="2"
                    controls-position="right"
                    placeholder="请输入"
                    clearable
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="单位" prop="purchaseUnit">
                  <px-select v-model="equipdata.purchaseUnit" placeholder="请选择" clearable style="width: calc(100% - 100px)" filterable>
                    <px-option v-for="dict in unitList" :key="dict.id" :label="dict.itemName" :value="dict.itemName" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="剩余可购入数量">
                  <px-input-number
                    v-model="equipdata.remainQuantity"
                    style="width: calc(100% - 100px)"
                    :disabled="true"
                    :precision="5"
                    controls-position="right"
                    placeholder="请输入"
                    clearable
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="有效时间" style="width: calc(100% - 100px)" prop="timevalue">
                  <px-date-picker
                    v-model="equipdata.timevalue"
                    type="datetimerange"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :default-time="defaultTime" /></px-form-item
              ></px-col>
              <px-col :span="8">
                <px-form-item label="限次类型" prop="limitTimesType">
                  <px-select v-model="equipdata.limitTimesType" placeholder="请选择限次类型" clearable style="width: calc(100% - 100px)" filterable>
                    <px-option v-for="dict in limitTimesTypeList" :key="dict.itemValue" :label="dict.itemName" :value="dict.itemValue" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="办理人" prop="responsiblePersonId">
                  <px-select
                    v-model="equipdata.responsiblePersonId"
                    placeholder="请选择"
                    style="width: calc(100% - 100px)"
                    clearable
                    filterable
                    @change="changeresponsiblePerson"
                  >
                    <px-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
            </px-row>
          </div>
        </div>

        <div
          class="box-card2"
          :style="{
            height: jiqicanshuFlg == true ? '' : '42px'
          }"
        >
          <div class="card-header" @click="setjiqicanshuFlg()">
            <div class="card-title">购买证</div>
            <div class="card-main">
              <px-icon v-if="!jiqicanshuFlg"><ArrowDown /></px-icon>
              <px-icon v-else><ArrowUp /></px-icon>
            </div>
          </div>
          <px-scrollbar class="form-div">
            <div class="info-form-content">
              <PhotoUpload
                :key="'ptoto1'"
                photoType="add"
                :photoData="{ moduleName: 'GENERAL_CHEMICALS' }"
                :photoList="equipdata.permitAttachment"
                @changePhotoList="changePhotoList1"
                @savePhotoStatus="savePhotoStatus1"
              />
            </div>
          </px-scrollbar>
        </div>
        <div
          class="box-card2"
          :style="{
            height: shebeitaizhangFlg == true ? '' : '42px'
          }"
        >
          <div class="card-header" @click="setshebeitaizhangFlg()">
            <div class="card-title">合法使用证明</div>
            <div class="card-main">
              <px-icon v-if="!shebeitaizhangFlg"><ArrowDown /></px-icon>
              <px-icon v-else><ArrowUp /></px-icon>
            </div>
          </div>
          <px-scrollbar class="form-div">
            <div class="info-form-content">
              <div class="legalAttachment">
                <PhotoUpload
                  :key="'ptoto2'"
                  photoType="add"
                  :photoData="{ moduleName: 'GENERAL_CHEMICALS' }"
                  :photoList="equipdata.legalAttachment"
                  @changePhotoList="changePhotoList2"
                  @savePhotoStatus="savePhotoStatus2"
                />
              </div>
            </div>
          </px-scrollbar>
        </div>
      </px-form>
    </px-scrollbar>
    <div v-if="equipopenDetail" v-loading="subLoading" class="px-dialog-footer">
      <px-button @click="equipopenDetailcancel">取消</px-button>
      <px-button v-if="fromdisable" type="primary" @click="equipopenDetailcancel">关闭</px-button>
      <px-button v-else type="primary" :disabled="photoStatusFlag || fileStatusFlag" @click="equipopenDetailsubmitForm(detailruleFormRef)"
        >保存</px-button
      >
    </div>
    <px-dialog v-model="progressVisible" draggable clickHideContent title="上传进度" width="30%" center align-center>
      <px-progress :percentage="Math.floor(progressPercent)" />
    </px-dialog>
  </div>
</template>

<script setup name="Dict" lang="ts">
// import useDictStore from '@/store/modules/dict'
defineOptions({
  name: "SystemDataDict"
});
// import { router } from "@/router";
import { ArrowLeft } from "@px-ui/icons-vue";
import { useRoute } from "vue-router";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, ref, toRefs, reactive, onMounted } from "vue";
import { getToken } from "@/utils/auth";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import FileUpload from "@/components/Upload/FileUpload.vue";
import { queryChildByTypeCodeAndItemValue, liquidFileDelete } from "@/api/waterClass";
import {
  generalqueryDetail,
  precursorChemicalPurchasePermitqueryListPage,
  precursorChemicalPurchasePermitadd,
  precursorChemicalPurchasePermitdelete,
  precursorChemicalPurchasePermitupdate,
  precursorChemicalPurchasePermitqueryDetail,
  precursorChemicalPurchasePermitqueryChemicalList
} from "@/api/chemicals";
import { userlistPage } from "@/api/waterQualityDetection";
const options = [
  {
    itemValue: "system1",
    itemName: "系统1"
  },
  {
    itemValue: "system2",
    itemName: "系统2"
  }
];
const jibenxinxiFlg = ref(true);
const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 1), new Date(2000, 1, 1, 23, 59, 59)];
const changeresponsiblePerson = val => {
  userList.value.forEach(item => {
    if (item.value == val) {
      console.log(item);
      equipdata.value.responsiblePerson = item.label;
    }
  });
};

const changechemicalCode = val => {
  querychemicalList.value.forEach(item => {
    if (item.chemicalCode == val) {
      console.log(item);
      equipdata.value.chemical = item.chemical;
    }
  });
};

const setqingdanFlg = () => {
  jibenxinxiFlg.value = !jibenxinxiFlg.value;
};
const jiqicanshuFlg = ref(true);
const setjiqicanshuFlg = () => {
  jiqicanshuFlg.value = !jiqicanshuFlg.value;
};
const shebeitaizhangFlg = ref(true);
const setshebeitaizhangFlg = () => {
  shebeitaizhangFlg.value = !shebeitaizhangFlg.value;
};
const moxingshezhiFlg = ref(true);
const setmoxingshezhiFlg = () => {
  moxingshezhiFlg.value = !moxingshezhiFlg.value;
};

const setreceiveCompanyCode = val => {
  let setvalue = null;
  setvalue = liquidList.value.find(option => option.itemValue == val);
  if (setvalue && setvalue?.itemDesc != "") {
    queryParams.value.receiveCompanyCode = JSON.parse(setvalue.itemDesc).receiveCompanyCode;
  } else {
    queryParams.value.receiveCompanyCode = "";
  }
  //console.log(setvalue);
};

const setAddreceiveCompanyCode = val => {
  let setvalue = null;
  setvalue = liquidList.value.find(option => option.itemValue == val);
  if (setvalue && setvalue.itemDesc != "") {
    equipdata.value.receiveCompanyCode = JSON.parse(setvalue.itemDesc).receiveCompanyCode;
  } else {
    // equipdata.value.receiveCompanyCode = "";
  }
  //console.log(setvalue);
};
const route = useRoute();
onMounted(() => {
  if (route.query.equipmentId) {
    handleDetail(route.query.equipmentId);
  }
});
const { proxy }: any = getCurrentInstance();

const typeList = ref([]);
const detailruleFormRef = ref();
const progressVisible = ref(false);
const open = ref(false);
const equipopen = ref(false);
const equipopenDetail = ref(false);
const fromdisable = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const typeIdloading = ref(false);
const total = ref(0);
const progressPercent = ref(0);
const title = ref("");
const dateRange = ref([]);

// 图片是否上传完，是否可以保存
const savePhotoStatus1 = val => {
  console.log(val);
  photoStatusFlag.value = val;
};
const savePhotoStatus2 = val => {
  photoStatusFlag.value = val;
};
const savePhotoStatus3 = val => {
  photoStatusFlag.value = val;
};
const savePhotoStatus4 = val => {
  photoStatusFlag.value = val;
};
// 文件是否上传完，是否可以保存
const saveFileStatus = val => {
  fileStatusFlag.value = val;
};

const waterstatusList = [
  {
    value: "VALID",
    name: "全部"
  },
  {
    value: "INVALID",
    name: "已删除"
  }
];
const limitTimesTypeList = [
  {
    itemName: "单次有效",
    itemValue: "SINGLE"
  },
  {
    itemName: "多次有效",
    itemValue: "MANY"
  }
];
const buttonTitle = ref("");
const data = reactive({
  liquidList: [],
  storeList: [],
  sellList: [],
  transportCompanyList: [],
  receiveCompanyList: [],
  typeIdList: [],
  categoryList: [],
  equipmentTypeList: [],
  positionList: [],
  equipmentDeptList: [],
  modelIdList: [],
  form: {},
  photoStatusFlag: false,
  fileStatusFlag: false,
  equipdata: {
    id: "",
    permitOutNumber: "",
    chemicalCode: "",
    chemical: "",
    purchaseUnit: "",
    totalQuantity: "",
    remainQuantity: "",
    effectiveDateFrom: "",
    effectiveDateTo: "",
    limitTimesType: "",
    salesCompany: "",
    responsiblePersonId: "",
    responsiblePerson: "",
    permitAttachment: [],
    legalAttachment: [],
    timevalue: [],
    updateTime: "",
    permitNumber: ""
  },
  queryParams: {
    orderByColumn: "",
    isAsc: "",
    chemical: "",
    dateFrom: "",
    dateTo: "",
    orderBy: "",
    pageNum: 1,
    pageSize: 20
  },
  rules: {
    permitOutNumber: [{ required: true, message: "购买证编码不能为空", trigger: "blur" }],
    chemicalCode: [{ required: true, message: "化学品名称不能为空", trigger: "blur" }],
    salesCompany: [{ required: true, message: "销售单位不能为空", trigger: "blur" }],
    totalQuantity: [{ required: true, message: "可购入数量不能为空", trigger: "blur" }],
    timevalue: [{ required: true, message: "有效时间不能为空", trigger: "change" }],
    purchaseUnit: [{ required: true, message: "单位不能为空", trigger: "change" }],
    limitTimesType: [{ required: true, message: "限次类型为空", trigger: "change" }],
    responsiblePersonId: [{ required: true, message: "办理人不能为空", trigger: "change" }]
  },
  headers: {
    Authorization: "Bearer " + getToken().accessToken || ""
  },
  moduleName: "",
  dialogImageUrl: "",
  imageVisible: false,
  chemicalList: [],
  querychemicalList: [],
  unitList: [
    {
      id: 1587,
      typeId: "WTTS",
      itemName: "吨",
      itemValue: "TON",
      itemDesc: "",
      parentId: "CHEMICAL_UNIT",
      level: 2,
      itemSort: 0,
      status: "VALID",
      remark: "",
      createTime: "2024-09-18 14:16:43",
      updateTime: "2024-09-18 14:16:43",
      children: null
    }
  ],
  userList: [],
  salesCompanyList: []
});

const {
  salesCompanyList,
  liquidList,
  transportCompanyList,
  receiveCompanyList,
  queryParams,
  form,
  rules,
  equipdata,
  typeIdList,
  equipmentTypeList,
  modelIdList,
  dialogImageUrl,
  imageVisible,
  storeList,
  sellList,
  photoStatusFlag,
  fileStatusFlag,
  chemicalList,
  unitList,
  userList,
  querychemicalList
} = toRefs(data);
const handleRemove = file => {
  equipdata.value.attachment = equipdata.value.attachment.filter(item => item !== file);
  let parmas = {
    fileId: file.fileId ? file.fileId : file?.response?.data?.fileId,
    ledgerCode: equipdata.value.ledgerCode
  };
  liquidFileDelete(parmas).then((response: any) => {
    // //console.log(response);
    PxMessage({
      type: "success",
      message: "删除成功"
    });
  });
};
const checkTime = () => {
  if (equipdata.value.manufactureDate && equipdata.value.warrantyEndDate) {
    if (equipdata.value.manufactureDate > equipdata.value.warrantyEndDate) {
      PxMessage({
        message: "开始时间不能大于结束时间",
        type: "error"
      });
    }
  }
};
const getqueryCategoryList = () => {
  precursorChemicalPurchasePermitqueryChemicalList({}).then(res => {
    console.log(res);
    querychemicalList.value = res;
  });
  userlistPage({ page: 1, pageSize: 9999, deptNameList: ["WATER"], status: 0 }).then((response: any) => {
    userList.value = response.data.map(item => ({ label: `${item.username}-${item.realName}`, value: item.userId }));
    console.log(response);
  });
  queryChildByTypeCodeAndItemValue({
    value: "WATER_SYSTEM",
    typeCode: "WTTS"
  }).then((response: any) => {
    //console.log(response);
    liquidList.value = response;
  });
  queryChildByTypeCodeAndItemValue({
    value: "WATER_CHEMICAL_SUPPLIER",
    typeCode: "WTTS"
  }).then((response: any) => {
    //console.log(response);
    salesCompanyList.value = response;
  });
  //化学品单位
  // queryChildByTypeCodeAndItemValue({
  //   value: "CHEMICAL_UNIT",
  //   typeCode: "WTTS"
  // }).then((response: any) => {
  //   //console.log(response);
  //   unitList.value = response;
  // });
  //运输单位
  queryChildByTypeCodeAndItemValue({
    value: "TU01",
    typeCode: "WTTS"
  }).then((response: any) => {
    //console.log(response);
    transportCompanyList.value = response;
  });
  //接收单位
  queryChildByTypeCodeAndItemValue({
    value: "RU01",
    typeCode: "WTTS"
  }).then((response: any) => {
    //console.log(response);
    receiveCompanyList.value = response;
  });
  //存储地点
  queryChildByTypeCodeAndItemValue({
    value: "SL01",
    typeCode: "WTTS"
  }).then((response: any) => {
    //console.log(response);
    storeList.value = response;
  });
  //销售单位
  queryChildByTypeCodeAndItemValue({
    value: "SU01",
    typeCode: "WTTS"
  }).then((response: any) => {
    //console.log(response);
    sellList.value = response;
  });
};
getqueryCategoryList();
function getList() {
  loading.value = true;
  if (dateRange.value != null) {
    queryParams.value.dateFrom = dateRange.value[0];
    queryParams.value.dateTo = dateRange.value[1];
  } else {
    queryParams.value.dateFrom = "";
    queryParams.value.dateTo = "";
  }

  precursorChemicalPurchasePermitqueryListPage(queryParams.value).then((response: any) => {
    typeList.value = response.data;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  equipopen.value = false;
  subLoading.value = false;
}
function equipopenDetailcancel() {
  equipopenDetail.value = false;
  subLoading.value = false;
}
/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    dictionaryName: undefined,
    dictionaryType: undefined,
    status: "VALID",
    remarks: undefined
  };
  proxy.resetForm("dictRef");
}
/** 搜索按钮操作 */
function handleQuery(type) {
  if (type == "search") {
    queryParams.value.pageNum = 1;
  }
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    orderByColumn: "",
    isAsc: "",
    chemical: "",
    dateFrom: "",
    dateTo: "",
    orderBy: ""
  };
  dateRange.value = [];
  // querychemicalList.value = [];
  handleQuery("reset");
}

/** 新增按钮操作 */
function handleAdd() {
  buttonTitle.value = "新增";
  jibenxinxiFlg.value = true;
  jiqicanshuFlg.value = true;
  shebeitaizhangFlg.value = true;
  moxingshezhiFlg.value = true;
  equipopenDetail.value = true;
  fromdisable.value = false;
  equipmentTypeList.value = [];
  modelIdList.value = [];
  equipdata.value = {
    id: "",
    permitOutNumber: "",
    chemicalCode: "",
    chemical: "",
    purchaseUnit: "",
    totalQuantity: "",
    remainQuantity: "",
    effectiveDateFrom: "",
    effectiveDateTo: "",
    limitTimesType: "",
    salesCompany: "",
    responsiblePersonId: "",
    responsiblePerson: "",
    permitAttachment: [],
    legalAttachment: [],
    timevalue: [],
    updateTime: "",
    permitNumber: ""
  };
  equipdata.value.responsiblePersonId = JSON.parse(localStorage.getItem("userInfo")).userId;
  equipdata.value.responsiblePerson = `${JSON.parse(localStorage.getItem("userInfo")).username}-${JSON.parse(localStorage.getItem("userInfo")).realName}`;
}

const handleDetail = async val => {
  jibenxinxiFlg.value = true;
  jiqicanshuFlg.value = true;
  shebeitaizhangFlg.value = true;
  moxingshezhiFlg.value = true;
  const data = await precursorChemicalPurchasePermitqueryDetail({ id: val });
  //console.log(data);

  equipopen.value = true;
  // equipopenDetail.value = true;
  fromdisable.value = true;
  equipdata.value = data;
  equipdata.value.responsiblePersonId = data.responsiblePersonId != "" ? Number(data.responsiblePersonId) : "";
  equipdata.value.timevalue = [data.effectiveDateFrom, data.effectiveDateTo];
  if (data?.permitAttachment && data?.permitAttachment.length > 0) {
    data?.permitAttachment.forEach(item => {
      item.url = item.fileUrl;
      item.name = item.originalName;
    });
    equipdata.value.permitAttachment = data?.permitAttachment;
  } else {
    equipdata.value.permitAttachment = [];
  }
  if (data.legalAttachment && data.legalAttachment.length > 0) {
    data.legalAttachment.forEach(item => {
      item.url = item.fileUrl;
      item.name = item.originalName;
    });
    equipdata.value.legalAttachment = data.legalAttachment;
    console.log(equipdata.value.legalAttachment);
  } else {
    equipdata.value.legalAttachment = [];
  }
};

const handleEditor = async val => {
  buttonTitle.value = "编辑";
  jibenxinxiFlg.value = true;
  jiqicanshuFlg.value = true;
  shebeitaizhangFlg.value = true;
  moxingshezhiFlg.value = true;

  const data = await precursorChemicalPurchasePermitqueryDetail({ id: val });
  // console.log(data);
  equipopenDetail.value = true;
  fromdisable.value = false;
  equipdata.value = data;
  equipdata.value.responsiblePersonId = data.responsiblePersonId != "" ? Number(data.responsiblePersonId) : "";
  equipdata.value.timevalue = [data.effectiveDateFrom, data.effectiveDateTo];
  if (data?.permitAttachment && data?.permitAttachment.length > 0) {
    data?.permitAttachment.forEach(item => {
      item.url = item.fileUrl;
      item.name = item.originalName;
    });
    equipdata.value.permitAttachment = data?.permitAttachment;
  } else {
    equipdata.value.permitAttachment = [];
  }
  if (data.legalAttachment && data.legalAttachment.length > 0) {
    data.legalAttachment.forEach(item => {
      item.url = item.fileUrl;
      item.name = item.originalName;
    });
    equipdata.value.legalAttachment = data.legalAttachment;
    console.log(equipdata.value.legalAttachment);
  } else {
    equipdata.value.legalAttachment = [];
  }
};
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
// 新的图片列表
const changePhotoList1 = val => {
  equipdata.value.permitAttachment = val;
  console.log(val);
};
const changePhotoList2 = val => {
  equipdata.value.legalAttachment = val;
};
const changePhotoList3 = val => {
  equipdata.value.specificWeightPhoto = val;
};
// 新的文件列表
const changeFileList = val => {
  equipdata.value.testingFile = val;
};
/** 提交按钮 */
const subLoading = ref(false);
const equipopenDetailsubmitForm = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      subLoading.value = true;
      const params = {
        id: equipdata.value.id,
        permitOutNumber: equipdata.value.permitOutNumber,
        chemicalCode: equipdata.value.chemicalCode,
        chemical: equipdata.value.chemical,
        purchaseUnit: equipdata.value.purchaseUnit,
        totalQuantity: equipdata.value.totalQuantity,
        // remainQuantity: equipdata.value.remainQuantity,
        effectiveDateFrom: equipdata.value.timevalue[0],
        effectiveDateTo: equipdata.value.timevalue[1],
        limitTimesType: equipdata.value.limitTimesType,
        salesCompany: equipdata.value.salesCompany,
        responsiblePersonId: equipdata.value.responsiblePersonId,
        responsiblePerson: equipdata.value.responsiblePerson,
        updateTime: equipdata.value.updateTime,
        permitAttachment: equipdata.value.permitAttachment,
        legalAttachment: equipdata.value.legalAttachment,
        permitNumber: equipdata.value.permitNumber
      };
      console.log(equipdata.value.timevalue);
      if (equipdata.value.timevalue != null) {
        if (equipdata.value.timevalue.length > 0) {
          params.effectiveDateFrom = equipdata.value.timevalue[0];
          params.effectiveDateTo = equipdata.value.timevalue[1];
        }
      }
      if (buttonTitle.value == "新增") {
        if (params.permitAttachment.length > 0) {
          params.permitAttachment = params.permitAttachment.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        }
        if (params.legalAttachment.length > 0) {
          params.legalAttachment = params.legalAttachment.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        }

        precursorChemicalPurchasePermitadd(params)
          .then((response: any) => {
            PxMessage({
              message: `${buttonTitle.value == "新增" ? "添加成功" : "修改成功"}`,
              type: "success"
            });
            resetQuery();
            subLoading.value = false;
            equipopenDetail.value = false;
          })
          .catch(() => {
            subLoading.value = false;
          });
      } else {
        if (params.permitAttachment.length > 0) {
          params.permitAttachment = params.permitAttachment.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        }
        if (params.legalAttachment.length > 0) {
          params.legalAttachment = params.legalAttachment.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        }
        precursorChemicalPurchasePermitupdate(params)
          .then((response: any) => {
            PxMessage({
              message: `${buttonTitle.value == "新增" ? "添加成功" : "修改成功"}`,
              type: "success"
            });
            resetQuery();
            subLoading.value = false;
            equipopenDetail.value = false;
          })
          .catch(() => {
            subLoading.value = false;
          });
      }
    }
  });
};
/** 删除按钮操作 */
function handleDelete(row) {
  //console.log(row);
  // const dictIds = [];
  // if (row.equipmentId != undefined) {
  //   dictIds.push(row.equipmentId);
  // } else {
  //   dictIds.push(...ids.value);
  // }
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const data = await precursorChemicalPurchasePermitdelete({ id: row.id });
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
    })
    .catch(() => {});
}
const { VITE_FANRUAN_BASE_URL, VITE_SERVE_API_STATIC_URL } = import.meta.env;
/** 导出按钮操作 */
function handleExport() {
  if (dateRange.value != null && dateRange.value.length > 0) {
    let Token = getToken().accessToken || "";
    // proxy.download("post", "/operation/api/v1/water/testQuality/pwMetalImpurity/export", queryParams.value, "水质检测-纯水金属阴阳离子.xlsx");
    let url = `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report?viewlet=water%252F%25E5%2585%25B6%25E4%25BB%2596%25E5%258C%2596%25E5%25AD%25A6%25E5%2593%2581%25E8%25BD%25BD%25E8%25BF%259B%25E5%258F%25B0%25E8%25B4%25A6-FAC%2BWater.cpt&token=${Token}&from=${dateRange.value[0]}&to=${dateRange.value[1]}&chemical=${queryParams.value.chemical}&systemCode=${queryParams.value.systemCode}&location&format=excel&extype=simple&facCode=${localStorage.getItem("facCode") || ""}&apiHost=${VITE_SERVE_API_STATIC_URL}`;
    window.location.href = url;
  } else {
    PxMessage({
      message: "请选择时间后再导出",
      type: "error"
    });
  }
}

getList();
</script>
<style scoped lang="scss">
.addEquip {
  position: absolute;
  top: 0;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.editorEquip {
  position: absolute;
  top: 0;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.px-dialog-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 2002;
  width: 100%;
  height: 50px;
  padding-top: 10px;
  padding-right: 34px;
  text-align: right;
  background: white;
  box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
}

.card-header {
  min-height: 40px;
  padding: 14px 15px 7px !important;
  cursor: pointer;
  user-select: none;
  background: #e7eefb;
}

.card-title {
  float: left;
  line-height: 14px;
}

.card-main {
  float: left;
  margin: -3px 8px 0 5px;
  cursor: pointer;
}

.box-card1 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card2 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card3 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card4 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.demo-form-inline {
  .px-input {
    --px-input-width: calc(100% - 100px);
  }

  .px-form-item {
    width: 100%;
  }

  .px-textarea__inner {
    width: calc(100% - 100px) !important;
  }

  .px-form-item__label {
    font-weight: 400 !important;
  }
}

.form-div {
  padding: 24px;

  .px-row {
    margin-bottom: 16px;
  }
}

.px-icon {
  font-size: 16px !important;
}

:deep(.px-tabs__header) {
  // padding-left: 6px !important;
}

:deep(.px-tabs--top .px-tabs__item.is-top.is-active) {
  border: none;

  .pane-bottom {
    line-height: 30px;
    border-bottom: 2px solid #3b82f6;
  }
}

:deep(.px-tabs .px-tabs__item) {
  .pane-bottom {
    line-height: 30px;
  }
}

.pane-line {
  position: absolute;
  top: 12px;
  right: 0;
  height: 15px;
  color: #dcdcdc;
  border-left: 1px solid #dcdcdc;
}

:deep(.custom-form-ui .px-form-item) {
  width: 250px !important;
}

:deep(.px-upload-list--picture-card .px-upload-list__item) {
  width: 96px;
  height: 96px;
}

.filename {
  position: absolute;
  bottom: -30px;
  width: 96px;
  overflow: hidden;
  color: rgb(166 167 172);
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.px-descriptions__label.px-descriptions__cell.is-bordered-label) {
  width: 166px;
  background: #e7eefb;
  border: 1px solid #dfdfdf;
}

:deep(.px-descriptions__body .px-descriptions__table.is-bordered .px-descriptions__cell) {
  border: 1px solid #dfdfdf;
}

.cell-item {
  text-align: right;
}

:deep(.px-table__header) {
  thead {
    tr {
      background-color: #e7eefb !important;

      th {
        font-size: 14px;
        font-weight: bold;
        color: #000;
        background-color: #e7eefb !important;
      }
    }
  }
}

:deep(.px-table--isfixedHeader .px-table__header-wrapper .px-table-fixed-column--right) {
  background-color: #e7eefb !important;
}

.center2 {
  :deep(.px-descriptions__body) {
    table {
      border-left: none;

      .is-bordered-label {
        border-left: none !important;
      }
      // .is-bordered-content {
      //   border-right: none !important;
      // }
    }
  }
}

.status-value {
  color: #10b981;
}

.status-icon {
  display: inline-block;
  width: 8px;
  height: 8px;
  margin-right: 8px;
  background: #10b981;
  border-radius: 50%;
}

.status-value2 {
  color: red;
}

.status-icon2 {
  display: inline-block;
  width: 8px;
  height: 8px;
  margin-right: 8px;
  background: red;
  border-radius: 50%;
}
</style>
